package com.yuncommunity.cloudlab.utils

import org.apache.http.HttpEntity
import org.apache.http.NameValuePair
import org.apache.http.client.HttpClient
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import java.util.*
import javax.servlet.http.HttpServletRequest


object IpUtils {
    fun getIpAddr(request: HttpServletRequest): String {
        var ip: String? = request.getHeader("x-forwarded-for")
        if (ip == null || ip.length == 0 || "unknown".equals(ip, ignoreCase = true)) {
            ip = request.getHeader("Proxy-Client-IP")
        }
        if (ip == null || ip.length == 0 || "unknown".equals(ip, ignoreCase = true)) {
            ip = request.getHeader("WL-Proxy-Client-IP")
        }
        if (ip == null || ip.length == 0 || "unknown".equals(ip, ignoreCase = true)) {
            ip = request.getRemoteAddr()
        }
        return ip!!
    }

    fun getAddressResult(ip: String?): String {
        // 创建默认http连接
        val client: HttpClient = HttpClients.createDefault()
        // 创建一个post请求
        val post = HttpPost("http://api.map.baidu.com/location/ip")
        val paramList: MutableList<NameValuePair> = ArrayList<NameValuePair>()
        // 传递的参数
        paramList.add(BasicNameValuePair("ip", ip))
        paramList.add(BasicNameValuePair("ak", "7wW3T12KcytaMYf5muszGMHARuv2F6rE"))
        paramList.add(BasicNameValuePair("sn", ""))
        paramList.add(BasicNameValuePair("coor", ""))
        var address = ""
        try {
            // 把参转码后放入请求实体中
            val entitya: HttpEntity = UrlEncodedFormEntity(paramList, "utf-8")
            post.entity = entitya // 把请求实体放post请求中
            // 用http连接去执行get请求并且获得http响应
            val response = client.execute(post)
            // 从response中取到响应实体
            val entity: HttpEntity = response.entity
            // 把响应实体转成文本
            val str = EntityUtils.toString(entity)

            // 分隔解析
            if (str.length > 0) {
                val index = str.indexOf("province")
                val index2 = str.indexOf("city")
                val index3 = str.indexOf("district")
                val province = str.substring(index + 11, index2 - 3)
                val city = str.substring(index2 + 7, index3 - 3)
                address = decodeUnicode(province).toString() + "," + decodeUnicode(city)
            }
        } catch (e: Exception) {
            println(e)
        }
        return address
    }

    fun decodeUnicode(theString: String): String? {
        val sb = StringBuffer()

        val hex = theString.split("\\u")

        for (i in 1 until hex.size) {
            val data = hex[i].toInt(16)
            sb.append(data.toChar())
        }
        return sb.toString()
    }
}